package com.lxj.student_security.utils;

import com.lxj.student_security.entity.vo.Tree;
import io.swagger.models.auth.In;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BuildTree {
    public static <T> Tree<T> build(List<Tree<T>> nodes) {
        if (nodes == null) {
            return null;
        }
        /**
         * 定义一个
         */
        List<Tree<T>> topNodes = new ArrayList<>();
        for (Tree<T> children : nodes) {
            Integer pid = children.getPid();
            if (pid == null || pid == 0) {
                topNodes.add(children);
                continue;
            }
            for (Tree<T> parent : nodes) {
                Integer id = parent.getId();
                if (id != null && id == pid) {
                    parent.getChildren().add(children);
                    children.setHasParent(true);
                    parent.setHasChildren(true);
                    continue;
                }
            }
        }
        Tree<T> root = new Tree<T>();
        if (topNodes.size() == 1){
            root=topNodes.get(0);
        }else {
            root.setId(0);
            root.setPid(null);
            root.setHasParent(false);
            root.setHasChildren(true);
            root.setChecked(true);
            root.setChildren(topNodes);
            Map<String,Object> state = new HashMap<>(16);
            state.put("opened",true);
            root.setStatus(state);
        }
        return root;
    }
}
